package com.imy.alscript;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.storage.StorageManager;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.imy.virtual.client.core.InstallStrategy;
import com.imy.virtual.client.core.VirtualCore;
import com.imy.virtual.client.stub.VASettings;
import com.imy.virtual.helper.compat.NativeLibraryHelperCompat;
import com.imy.virtual.helper.utils.AppUtils;
import com.imy.virtual.helper.utils.LaunchIntentUtils;
import com.imy.virtual.remote.InstallResult;
import com.imy.virtual.server.pm.parser.PackageParserEx;
import com.imy.virtual.server.pm.parser.VPackage;
import com.imy.alscript.models.AppInfo;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import mirror.dalvik.system.VMRuntime;
import mirror.java.io.DefaultFileSystem;
import mirror.java.io.FileSystem;

public class KBAPKListActivity extends AppCompatActivity {

  private ListView mListView;
  private PathListAdapter adapter;

  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_install_a_p_k);
    mListView = findViewById(R.id.list_view);
    //读取APK文件
    new Thread(() -> {
      List<AppInfo> data = getData();
      runOnUiThread(() -> {
        //设置数据
        adapter = new PathListAdapter(KBAPKListActivity.this, data);
        mListView.setAdapter(adapter);
        adapter.setStartClickedListener(new PathListAdapter.StartClickedListener() {
          @Override
          public void onStart(AppInfo path) {
            start(path);
          }

          @Override
          public void onInstall(AppInfo path) {
            install(path);
          }

          @Override
          public void onCheckSo(AppInfo path) {
            int i = NativeLibraryHelperCompat.checkOnly64Support(path.path, VMRuntime.is64Bit.call(VMRuntime.getRuntime.call()));
            if (i==NativeLibraryHelperCompat.ONLY_SUPPORT_64){
              Toast.makeText(KBAPKListActivity.this,"当前应用仅支持64位",Toast.LENGTH_SHORT).show();
            }else if (i==NativeLibraryHelperCompat.SUPPORT_32){
              Toast.makeText(KBAPKListActivity.this,"当前应用仅支持32",Toast.LENGTH_SHORT).show();
            }else if (i==NativeLibraryHelperCompat.SUPPORT_64_AND_32){
              Toast.makeText(KBAPKListActivity.this,"当前应用同时支持32和64",Toast.LENGTH_SHORT).show();
            }
          }
        });
      });
    }).start();
    VirtualCore.get().setAppRequestListener(new VirtualCore.AppRequestListener() {
      @Override
      public void onRequestInstall(String path) {
        Log.i("KBAPKListActivity", "onRequestInstall" + path);
      }

      @Override
      public void onRequestUninstall(String pkg) {

      }
    });
  }

  private void install(AppInfo path) {
    if (path.isInstall) {
      Toast.makeText(this, "应用已安装", Toast.LENGTH_LONG).show();
      return;
    }
    Toast.makeText(this, "即将开始安装", Toast.LENGTH_LONG).show();
    new Thread(() -> {
      Log.i("KBAPKListActivity", "install:" + path.path);
      InstallResult installResult = VirtualCore.get().installPackage(path.path, InstallStrategy.UPDATE_IF_EXIST);
      Log.i("KBAPKListActivity", "安装" + installResult.isSuccess);
      //通知更新UI

      updateUI(installResult,path);
    }).start();
  }

  private void updateUI(InstallResult installResult, AppInfo path) {
    runOnUiThread(() -> {
      if (installResult.isSuccess){
        List<AppInfo> lists = adapter.getLists();
        for (int i = 0; i < lists.size(); i++) {
          AppInfo appInfo = lists.get(i);
          if (appInfo.packageName.equals(installResult.packageName)) {
            appInfo.isInstall = true;
          }
        }
        adapter.notifyDataSetChanged();
      }else {
       Log.i("KBAPKListActivity","code:"+installResult.code);
       if (installResult.code==InstallResult.ONLY_SUPPORT_64BIT){
         //检查是否安装了app
         boolean b = AppUtils.check64SupportInstall(KBAPKListActivity.this);
         if (b){
           Log.i("KBAPKListActivity","已安装64支持");
           //启动64支持器
           start64Support(path);
         }else {
           Log.i("KBAPKListActivity","未已安装64支持");
           Toast.makeText(KBAPKListActivity.this,installResult.error,Toast.LENGTH_LONG).show();
         }
       }
      }
    });
  }

  private void start64Support(AppInfo path) {
    try {
      Intent intent=new Intent(Intent.ACTION_VIEW, Uri.parse("kykbsupport://open"));
      intent.putExtra(VASettings.APK_PATH,path.path);
      intent.putExtra(VASettings.APK_PACKAGE,path.packageName);
      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      startActivity(intent);
    }catch (Exception e){
      Log.i("KBAPKListActivity","e:"+e.getMessage());
      Toast.makeText(this,"启动64支持器失败，请确认是否安装了",Toast.LENGTH_LONG).show();
    }

  }

  private boolean isDoing = false;

  private void start(AppInfo info) {
    boolean appInstalled = VirtualCore.get().isAppInstalled(info.packageName);
    if (!appInstalled) {
      Toast.makeText(this, "该应用未安装，请先安装", Toast.LENGTH_LONG).show();
      return;
    }
    Toast.makeText(this, "即将启动", Toast.LENGTH_LONG).show();
    LoadingActivity.launch(getApplicationContext(), info.packageName, 0);
  }

  private List<AppInfo> getData() {
    final String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/HYKB/bazaar/";
    File file = new File(path);
    if (file.exists()) {
      try {
        File[] files = file.listFiles();
        List<String> apkPath = new ArrayList<>();

        if (files != null) {
          for (File value : files) {
            String absolutePath = value.getAbsolutePath();
            if (absolutePath.endsWith(".apk")) {
              apkPath.add(absolutePath);
            }
          }
          return getAppInfo(apkPath);
        } else {
          Log.i("KBAPKListActivity", "获取APK失败");
        }
      } catch (Exception e) {
        Log.i("KBAPKListActivity", "Exception:" + e.getMessage());
      }
    }

    return new ArrayList<>();
  }

  private List<AppInfo> getAppInfo(List<String> apkPath) {
    List<AppInfo> list = new ArrayList<>();
    for (int i = 0; i < apkPath.size(); i++) {
      String s = apkPath.get(i);
      AppInfo appInfo = new AppInfo();
      //需要解析出包名
      try {
        VPackage vPackage = PackageParserEx.parsePackage(new File(s));
        String packageName = vPackage.packageName;
        //查询是否安装
        appInfo.isInstall = VirtualCore.get().isAppInstalled(packageName);
        Drawable applicationIcon = VirtualCore.get().getPackageManager().
            getApplicationIcon(vPackage.applicationInfo);
        String[] split = s.split("/");
        String fileName = "unKnow";
        for (int j = 0; j < split.length; j++) {
          String s1 = split[j];
          Log.i("KBAPKListActivity", "s1:" + s1);
          if (s1.contains(".apk")) {
            fileName = s1.replace(".apk", "");
          }
        }
        appInfo.name = fileName;
        appInfo.path = s;
        appInfo.packageName = packageName;
        appInfo.icon = applicationIcon;
        list.add(appInfo);
      } catch (Throwable throwable) {
        throwable.printStackTrace();
      }
    }
    return list;
  }
}
